# -*- coding: utf-8 -*-
import json
import time
from dateutil.parser import parse

import requests
from config.config import FeiShuMsgUrl, FeiShuMsgFile, ReportUrl, release_hour
from utils import Tools


class FeiShu:
    def __init__(self, url=FeiShuMsgUrl, file=FeiShuMsgFile):
        self.url = url
        self.file = file
        self.msg = ''
        self.current_case = ''
        self.message_body = {'PASS': [], "FAIL": []}
        self.text = ''
        self.mentioned_mobile_list = []

    def send_msg(self):
        self.get_msg()
        payload_message = {
            "msgtype": "text",
            "text": {
                "content": self.text,
                "mentioned_mobile_list": self.mentioned_mobile_list
            }
        }
        headers = {
            'Content-Type': 'application/json'
        }
        # requests.request("POST", self.url["test"], headers=headers, data=json.dumps(payload_message))
        requests.request("POST", self.url["external"], headers=headers, data=json.dumps(payload_message))

    def get_msg(self):
        pass_num = 0
        fail_num = 0
        fail_msg = ''
        for each in self.message_body['PASS']:
            for p in each.keys():
                if "全局前置条件" in p:
                    pass
                else:
                    pass_num += 1
        for each in self.message_body['FAIL']:
            for f in each.keys():
                if "全局前置条件" in f:
                    pass
                else:
                    fail_num += 1
                    fail_msg += '%s:%s\n' % (str(f), str(each[f]))
        if fail_num == 0:
            self.text += "自动化接口巡检(生产): %d 通过\n" % pass_num
        else:
            self.text += "自动化接口巡检(生产): %d 通过\t%d 失败\n" % (
                pass_num, fail_num)
            self.mentioned_mobile_list = ["@all"]
        self.text += fail_msg
        self.text += '巡检报告: %s' % ReportUrl

    def get_msg_body(self, result, comparator, expected, res_obj_data, response_time_ms, msg=''):
        if not result:
            if comparator in ["eq", "equal", "Equal"]:
                expected_msg = '%s = %s' % (str(expected[0]), str(expected[1]))
                actual_msg = "%s = %s" % (str(expected[0]), str(Tools.get_target_value(res_obj_data, expected[0])))
            elif comparator in ["not_equal", "not_eq", "notEqual"]:
                expected_msg = "%s != %s" % (str(expected[0]), str(expected[1]))
                actual_msg = "%s != %s" % (str(expected[0]), str(Tools.get_target_value(
                    res_obj_data, expected[0])))
            elif comparator in ["in", "In"]:
                expected_msg = '响应包含%s' % str(expected[0])
                actual_msg = '结果请查看报告'
            elif comparator in ["not_in", "notIn"]:
                expected_msg = '响应不包含%s' % str(expected[0])
                actual_msg = '结果请查看报告'
            elif comparator == 'run_time':
                expected_msg = '响应时间 < %d' % int(expected)
                actual_msg = '响应时间为：%d ms' % int(response_time_ms)
            elif msg != '':
                expected_msg = expected
                actual_msg = '%s 结果请查看报告' % msg
            else:
                expected_msg = ''
                actual_msg = ''
            body = {
                self.current_case: '%s(预期:%s)' % (actual_msg, expected_msg)}
            for i in self.message_body['FAIL']:
                if self.current_case in i.keys():
                    self.message_body['FAIL'].remove(i)
            if body not in self.message_body["FAIL"]:
                self.message_body["FAIL"].append(body)
        else:
            body = {self.current_case: '测试通过'}
            if body not in self.message_body["PASS"]:
                self.message_body["PASS"].append(body)
            for i in self.message_body['FAIL']:
                if self.current_case in i.keys():
                    self.message_body['FAIL'].remove(i)
        fail_case = []
        for f in self.message_body['FAIL']:
            fail_case.append(list(f.keys())[0])
        for p in self.message_body["PASS"]:
            if list(p.keys())[0] in fail_case:
                self.message_body['PASS'].remove(p)


feishu_msg = FeiShu()
